package rcpexplorer.views;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;

public class CopyConfigurationElementAction implements IObjectActionDelegate {
	private IConfigurationElement configurationElement;
	private BEPEBView view;

	public CopyConfigurationElementAction() {
	}

	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		this.view = null;
		if (targetPart instanceof BEPEBView) {
			this.view = (BEPEBView)targetPart;
		}
	}

	public void run(IAction action) {
		if (configurationElement != null || view == null) {
			String xml = toXml(configurationElement);
			// Get Clipboard
			Clipboard clipboard = new Clipboard(PlatformUI.getWorkbench()
					.getActiveWorkbenchWindow().getShell().getDisplay());
			// Put the paths string into the Clipboard
			clipboard.setContents(new Object[] { xml },
					new Transfer[] { TextTransfer.getInstance() });
		}
	}

	private String toXml(IConfigurationElement configurationElement) {
		if (configurationElement == null) {
			return "";
		}
		
		StringBuilder stringBuilder = new StringBuilder();
		BEPEBView.toXml(configurationElement, stringBuilder);
		return stringBuilder.toString();
	}

	public void selectionChanged(IAction action, ISelection selection) {
		configurationElement = null;
		action.setEnabled(false);
		if (selection instanceof ITreeSelection) {
			ITreeSelection treeSelection = (ITreeSelection) selection;
			TreePath[] paths = treeSelection.getPaths();
			if (paths.length > 0) {
				Object lastSegment = paths[0].getLastSegment();
				if (lastSegment instanceof IConfigurationElement) {
					configurationElement = ((IConfigurationElement) lastSegment);
					action.setEnabled(true);
				}
			}
		}		
	}

}
